package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.UserDao;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.util.PasswordUtil;
import com.itheima.health.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author zhangmeng
 * @description 用户服务实现类
 * @date 2019/9/6
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private PasswordUtil passwordUtil;

    @Autowired
    private UserDao userDao;
    @Override
    public User findByUsername(String username) {
        //调用DAO查询数据
        return userDao.selectByUsername(username);
    }

    /**
     * 登录
     *
     * @param request
     * @param param
     * @return
     */
    @Override
    public Result login(HttpServletRequest request, LoginParam param) {
        //获取session
        HttpSession session = request.getSession();
        String username = param.getUsername();
        String password = param.getPassword();
        User user = userDao.selectByUsername(username);
        String passwordDb = user.getPassword();
        if ((password.equals(passwordDb))) {
            //登录成功
            session.setAttribute("userId", user.getId());
            return new Result(true, MessageConst.LOGIN_SUCCESS);
        } else if ("{bcrypt}".equals(passwordDb.substring(0, 8))) {
            if (passwordUtil.bcryptPasswordDecryption(password, passwordDb)) {
                //登录成功
                session.setAttribute("userId", user.getId());
                return new Result(true, MessageConst.LOGIN_SUCCESS);
            }
        } else if ("{md5}".equals(passwordDb.substring(0, 5))) {
            if (passwordUtil.md5PasswordDecryption(password, passwordDb)) {
                //登录成功
                session.setAttribute("userId", user.getId());
                return new Result(true, MessageConst.LOGIN_SUCCESS);
            }
        }
        return new Result(false, MessageConst.LOGIN_FAIL);
    }

    /**
     * 获取用户名
     *
     * @param request
     * @return
     */
    @Override
    public Result getUsername(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userId = session.getAttribute("userId").toString();
        User user = userDao.selectById(userId);
        return new Result(true, MessageConst.ACTION_SUCCESS, user.getUsername());
    }
}
